#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/un.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <time.h>
//
size_t const BUFSZ=512;
//
struct sockaddr_in  server;
int s;
//
void printUsage()
{
  printf("usage: recvd_tester host port file\n");
}
//
int main(int argc, char *argv[]){

  if(argc<4){
    printUsage();
    exit(1);
  }

  if((s=socket(PF_INET,SOCK_STREAM,0))<0){
    perror("socket");
    exit(1);
  }

  struct hostent *host;
  host=gethostbyname(argv[1]);
  if(host==NULL){
    u_long addr;
    addr=inet_addr(argv[1]);
    host=gethostbyaddr((char *)&addr,sizeof(addr),AF_INET);
    if(host==NULL){
      perror("gethostbyaddr");
      exit(1);
    }
  }
  memset((char *)&server,0,sizeof(server));
  server.sin_family=AF_INET;
  server.sin_port = htons(atoi(argv[2]));
  memcpy((char *)&server.sin_addr,host->h_addr,host->h_length);

  if(connect(s, (struct sockaddr *) &server, sizeof(server))<0){
    perror("connect");
    exit(1);
  }
  
  int ia=3;
  do{    
    printf("Opening: %s\n",argv[ia]);
    FILE *fin=fopen(argv[ia],"r");
    if(fin==NULL){
      perror("fopen");
    }else{
      char buf[BUFSZ];
      int bs;
      int sl;
      size_t n;
      size_t tn=0;
      double const maxran=2147483647.;
      do{
	double f=(double)random()/(maxran);
	double g=(double)random()/(maxran);
	bs=f*BUFSZ;
	if(bs<8) bs=8;
	bs=(bs/8)*8;
	n = fread(&buf,bs,1,fin);
	if(n==1){
	  if((n=send(s,buf,bs,0))==-1){
	    break;
	  }else{
	    tn+=n;
	  }
	    sl=g*500;
	    usleep(1);
	}
      }while(feof(fin)==0);
      printf("Sent: %lu\n",tn);
    }    
    ia++;
  } while(ia<argc);
  close(s);
  exit(1);
}
